from django.shortcuts import render
import json
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection
from apps.news.models import *
from apps.users.models import *


# Create your views here.


# 频道列表
class ChannelsView(View):
    def get(self, request):
        data_list = []
        channel = Channel.objects.all()
        count = channel.count()
        for item in channel:
            data_list.append({
                'id': item.id,
                'name': item.name
            })
        return JsonResponse({"count": count, "next": None, "previous": None, 'results': data_list})


# 文章列表
class ArticleView(View):
    def get(self, request, id):
        page = int(request.GET.get("page"))
        essay = Article.objects.filter(channel=id)
        count = essay.count()
        list = []
        for i in essay:
            articles = [{"id": i.id, "title": i.title} for i in i.user.articles.all()]
            fans = [i.id for i in User.objects.filter(fans=i.user)]
            collected_users = [i.id for i in i.collected_users.all()]
            list.append({
                "id": i.id,
                "title": i.title,
                "content": i.content,
                "createtime": i.createtime,
                "user":
                    {"id": i.user.id,
                    "username": i.user.username,
                    "avatar": 'http://s7g9jujrf.hn-bkt.clouddn.com/' +  i.user.avatar,
                    "articles": articles,
                    "fans": fans},
                "collected_users": collected_users,
                "image": i.image,
                "collected": True if request.user.id in collected_users else False
                })
        return JsonResponse({"count": count, "next": None, "previous": None, "results": list})